<template>
  <div>
    <el-upload
      :action="action"
      :before-upload="handleBeforeUpload"
      :on-success="onImportSuccess"
      :limit="1"
      :data="postData"
      :headers="headers"
      :show-file-list="false"
    >
      <el-button :icon="icon" :size="size" :type="type">{{ title }}</el-button>
    </el-upload>
    <loading-dialog v-model="isImporting" loading-text="正在导入，请稍等"/>
  </div>
</template>

<script>
import {getToken} from '@/utils/auth'
import LoadingDialog from '@/framework/components/dialog/LoadingDialog'
import { AppVersion } from '@/framework/constant/Common'

export default {
  name: 'FileUploader',
  components: {LoadingDialog},
  props: {
    postData: {
      type: Object,
      default() {
        return null
      }
    },
    action: {
      type: String,
      required: true
    },
    title: {
      type: String,
      default: '导入'
    },
    type: {
      type: String,
      default: 'default'
    },
    icon: {
      type: String,
      default: 'el-icon-document'
    },
    size: String
  },
  methods: {
    handleBeforeUpload() {
      this.isImporting = true
    },
    onImportSuccess(res, file, list) {
      list.length = 0
      this.isImporting = false
      if (res.code !== 200) {
        this.$message.error(res.msg)
        return
      }
      this.$$notify('导入成功')
      this.$emit('success')
    }
  },
  data() {
    return {
      headers: {
        Authorization: getToken(),
        token: getToken(),
        'AppVersion': AppVersion
      },
      isImporting: false
    }
  }
}
</script>

<style scoped>

</style>
